package nveces.jspwiki.plugins.svg;

import static nveces.jspwiki.plugins.svg.MagicNamesPluginSvg.JPEG_EXT;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.log4j.Logger;

import com.ecyrd.jspwiki.providers.ProviderException;

/**
 * $Id: Svg2Image.java 10 2011-02-26 20:48:09Z nveces@gmail.com $
 * @author nveces
 *
 */
public class Svg2Image {

    @SuppressWarnings("unused")
    private static final Logger log        = Logger.getLogger(Svg2Image.class);

    private Float               keyQuality = new Float(0.8);

    public Float getKeyQuality() {
        return keyQuality;
    }

    public void setKeyQuality(Float keyQuality) {
        this.keyQuality = keyQuality;
    }

    public StringBuffer dtranscode(StringBuffer workFile, InputStream is, String src) throws ProviderException, IOException, TranscoderException {
        workFile.append(File.separator);
        workFile.append(src);
        workFile.append(JPEG_EXT);
        JPEGTranscoder t = new JPEGTranscoder();
        t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, this.keyQuality);
        TranscoderInput input = new TranscoderInput(is);
        OutputStream os = new FileOutputStream(workFile.toString());
        TranscoderOutput output = new TranscoderOutput(os);
        t.transcode(input, output);
        os.flush();
        os.close();
        return workFile;
    }

    public StringBuffer dtranscode(String workFile, InputStream is, String src) throws ProviderException, IOException, TranscoderException {
        return this.dtranscode(new StringBuffer(workFile), is, src);
    }

    public byte[] dtranscode(InputStream is) throws TranscoderException, IOException {
        JPEGTranscoder t = new JPEGTranscoder();
        t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, this.keyQuality);
        TranscoderInput input = new TranscoderInput(is);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        TranscoderOutput output = new TranscoderOutput(baos);
        t.transcode(input, output);
        baos.flush();
        byte[] b = baos.toByteArray();
        baos.close();
        return b;
    }

}
